var http = require('http');
var parse = require('url').parse;
var path = require('path');
var fs = require('fs');
var mime = require('mime');

var qs = require('querystring');
var util = require('util');

var root = __dirname;


function serverHandler(req, res) {
	var url = parse(req.url);
	if (req.method === 'GET') {
		getResource(res, url);
	}
	else if (req.method === 'POST') {
		var postStr = '';
		req.setEncoding = 'utf8';
		req.on('data', function (chunk) { postStr += chunk; })
		req.on('end', function () {
			var obj = qs.parse(postStr);
			content = util.format(postStr);
			res.setHeader('Content-Type', 'text/plain');		
			res.setHeader('Content-Length', Buffer.byteLength(postStr));
			res.end(postStr);
		})	
	}    
}

function getResource(res, url) {
	var pathname = path.join(root, url.pathname);
	fs.stat(pathname, function (err, stat) {
		if (err) {
			if ('ENOENT' == err.code) {
				res.statusCode = 404;
				res.end('Not Found');
			}
			else {
				res.statusCode = 500;
				res.end('Internal Server Error');
			}
		}
		else {
			res.setHeader('Content-Length', stat.size);
			res.setHeader('Content-Type', mime.lookup(path.basename(pathname)));
			var stream = fs.createReadStream(pathname);
			stream.pipe(res);
			stream.on('error', function (err) {
				res.statusCode = 500;
				res.end('Internal Server Error');
			});
		}
	});
}


var io = require('socket.io');
var server = http.createServer(serverHandler);
var iosocket = io.listen(server);
iosocket.sockets.on('connection', connectHandler);
function connectHandler(socket) {
	console.log('connection');
	socket.on('login', function (data) {
		console.log('login' + data);
	});
	socket.on('message', function (data) {
		console.log('receive:' + data);
		socket.send('the message from server at localhost:4000');
	})
	socket.send('aa');
	fs.watchFile('./selectPic.css', {interval: 200}, function (cur, prev) {
		if (cur.mtime != prev.mtime) {
			socket.emit('reload');
		}
	})
	fs.watchFile('./selectPic.js', {interval: 200}, function (cur, prev) {
		if (cur.mtime != prev.mtime) {
			socket.emit('reload');
		}
	})
	socket.on('disconnect', disconnectHandler)
}

function disconnectHandler() {
	console.log('disconnect');
}

server.listen(4000);
console.log('Server start at localhost 4000');


var mongodb = require('mongodb');
var mongodbServer = new mongodb.Server('127.0.0.1', 27017, {});
var client = new mongodb.Db("test", mongodbServer, {w: 1});

client.open(function (err) {
	if (err) throw err;
	client.collection('users', function (err, collection) {
		if (err) throw err;
		console.log('we are now able to perform queries');

		collection.find().toArray(function(e, docs) {
			if (e) throw e;
			console.log(docs);
		})

		collection.insert({'title': 'i like cake'}, {safe: true}, function (err, documents) {
			if (err) throw err;
			console.log('document id is: ' + documents[0]);
		})
	})
	
})